package auction.chapter11;

import java.lang.reflect.Method;

import org.hibernate.FlushMode;
import org.hibernate.context.ManagedSessionContext;

import persistence.HibernateUtil;

/**
 * NOTE: the relationship between two Session
 * org.hibernate.Session
      org.hibernate.classic.Session
 * @author wei
 *
 */
public class ConversationInterceptor {
	public Object invoke(Method method) throws Exception{
		
		//Note: this one can be stored in Http Session
		org.hibernate.classic.Session disconnectedSession = null;
		
		org.hibernate.classic.Session currentSession = null;
		
		if(disconnectedSession == null){
			//Start of a new conversation
			currentSession=HibernateUtil.getSessionFactory().openSession();
			currentSession.setFlushMode(FlushMode.MANUAL);
		}else{
			//In the middle of a conversation
			currentSession = disconnectedSession;
		}
		
		//Bind before processing event
		ManagedSessionContext.bind(currentSession);
		
		currentSession.beginTransaction();
		
		Object result=method.invoke(null);//The DAO layer can call getCurrentSesion()
		
		currentSession=ManagedSessionContext.unbind(HibernateUtil.getSessionFactory());
		
		if(result == "finished"){
			currentSession.flush();
			currentSession.getTransaction().commit();
			currentSession.close();
			
			disconnectedSession = null;
		}else{
			currentSession.getTransaction().commit();
			disconnectedSession = currentSession;
			//user think time
		}
		
		return result;
		
	}
}